package com.choudou5.solr.web.handler.sys;

import cn.hutool.core.collection.CollUtil;
import com.choudou5.solr.annotation.ReqMapping;
import com.choudou5.solr.annotation.ReqMethod;
import com.choudou5.solr.api.IndexApi;
import com.choudou5.solr.bean.IndexInfoBean;
import com.choudou5.solr.bean.common.PageResult;
import com.choudou5.solr.bean.common.SqlQueryBean;
import com.choudou5.solr.bean.event.SolrEventConsumeBean;
import com.choudou5.solr.bean.event.SolrEventPublishBean;
import com.choudou5.solr.bean.sys.SysNoticeBean;
import com.choudou5.solr.core.util.SolrHelper;
import com.choudou5.solr.framework.bean.HttpRespBean;
import com.choudou5.solr.framework.bean.UserBean;
import com.choudou5.solr.framework.constants.ErrorResp;
import com.choudou5.solr.framework.constants.UserConsts;
import com.choudou5.solr.framework.util.PageJumpUtil;
import com.choudou5.solr.framework.util.RequestUtil;
import com.choudou5.solr.service.ServiceHelper;
import com.choudou5.solr.service.event.SolrEventConsumeService;
import com.choudou5.solr.service.event.SolrEventPublishService;
import com.choudou5.solr.service.sys.SysNoticeService;
import com.choudou5.solr.util.SolrJUtil;
import com.choudou5.solr.utils.SqlQueryBuilder;
import com.choudou5.solr.web.handler.BaseHandler;
import org.apache.solr.client.solrj.SolrQuery;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Name：系统管理 处理器
 * @Author：choudou5
 * @Date：2018-07-15
 */
public class SystemHandler extends BaseHandler {

    protected static SysNoticeService sysNoticeService =  ServiceHelper.singleton(SysNoticeService.class);
    protected static SolrEventPublishService eventPublishService = ServiceHelper.singleton(SolrEventPublishService.class);
    protected static SolrEventConsumeService eventConsumeService = ServiceHelper.singleton(SolrEventConsumeService.class);
    protected static IndexApi indndexApi = IndexApi.getInstance();

    @Override
    public void execute(String method, HttpServletRequest req, HttpServletResponse resp) {
        logger.info("SystemHandler method:{}", method);
        switch (method){
            case "userList":
                userList(req, resp);
                break;
            case "setUserStatus":
                setUserStatus(req, resp);
                break;
            case "indexList":
                indexList(req, resp);
                break;
            case "reIndex":
                reIndex(req, resp);
                break;
            case "noticeList":
                noticeList(req, resp);
                break;
            case "addNotice":
                addNotice(req, resp);
                break;
            case "offlineNotice":
                offlineNotice(req, resp);
                break;
            case "lastNotice":
                getLastNotice(req, resp);
                break;
            case "eventList":
                eventList(req, resp);
                break;
            case "eventConsumeList":
                eventConsumeList(req, resp);
                break;
            default:
                PageJumpUtil.errorOut(ErrorResp.Not_Found, req, resp);
                break;
        }
    }


    /****************************** 用户 begin *******************************************/

    /**
     * 用户列表
     * @param req
     * @param resp
     */
    private void userList(HttpServletRequest req, HttpServletResponse resp){
        SqlQueryBean sqlQueryBean = SqlQueryBuilder.buildWhereSql(req);
        PageResult<UserBean> pageResult = sysUserService.findPage(sqlQueryBean);
        req.setAttribute("pageResult", pageResult);
        PageJumpUtil.forward("userList", req, resp);
    }

    @ReqMapping(desc = "设置用户状态", method = ReqMethod.POST)
    private void setUserStatus(HttpServletRequest req, HttpServletResponse resp){
        if(isAdmin(req, resp)) {
            Integer userId = RequestUtil.getIntParameter(req, "userId");
            String status = RequestUtil.getStrParameter(req, "status");
            String reason = RequestUtil.getStrParameter(req, "reason");
            UserConsts.UserStatus userStatus = UserConsts.UserStatus.get(status);
            boolean valid = validParam(req, resp, new Object[]{userId, status, reason}, new String[]{"用户ID", "状态", "理由"});
            if(valid){
                sysUserService.updateStatus(userId, userStatus, reason);
                PageJumpUtil.writeJsonOk("设置成功", resp);
            }
        }
    }


    /****************************** 用户 end *******************************************/



    /****************************** 索引 begin *******************************************/

    /**
     * 索引列表
     * @param req
     * @param resp
     */
    private void indexList(HttpServletRequest req, HttpServletResponse resp){
        if(isAdmin(req, resp)){
            req.setAttribute("list", findIndexInfoList());
            PageJumpUtil.forward("indexList", req, resp);
        }
    }


    @ReqMapping(desc = "重建索引", method = ReqMethod.POST)
    private void reIndex(HttpServletRequest req, HttpServletResponse resp){
        String module = RequestUtil.getStrParameter(req, "module");
        if(!SolrHelper.existCoreName(module)){
            PageJumpUtil.errorOut(ErrorResp.INVALID_PARAM, "无效的模块", req, resp);
            return;
        }
        String message = indndexApi.reIndex(module);
        PageJumpUtil.writeJsonOk(message, resp);
    }


    public List<IndexInfoBean> findIndexInfoList(){
        Collection<String> coreNames = SolrHelper.getCoreNameList();
        if(CollUtil.isNotEmpty(coreNames)){
            List<IndexInfoBean> list = new ArrayList<>();
            SolrQuery solrQuery = new SolrQuery("*:*");
            long total = 0;
            for (String coreName : coreNames) {
                total = SolrJUtil.findTotal(solrQuery, SolrHelper.getCore(coreName));
                list.add(new IndexInfoBean(coreName, total));
            }
            return list;
        }
        return null;
    }

    /****************************** 索引 end *******************************************/


    /****************************** 公告 begin *******************************************/

    /**
     * 公告列表
     * @param req
     * @param resp
     */
    private void noticeList(HttpServletRequest req, HttpServletResponse resp){
        if(isAdmin(req, resp)){
            SqlQueryBean sqlQueryBean = SqlQueryBuilder.buildWhereSql(req);
            sqlQueryBean.setOrderDefParam("create_time", "DESC");
            PageResult<SysNoticeBean> pageResult = sysNoticeService.findPage(sqlQueryBean);
            req.setAttribute("pageResult", pageResult);
            PageJumpUtil.forward("noticeList", req, resp);
        }
    }

    @ReqMapping(desc = "保存公告", method = ReqMethod.POST)
    private void addNotice(HttpServletRequest req, HttpServletResponse resp){
        SysNoticeBean notice = buildBean(req, SysNoticeBean.class);
        boolean isNew = notice.isNew();
        sysNoticeService.save(notice);
        PageJumpUtil.writeJsonOk(isNew?"新增成功":"修改成功", resp);
    }

    @ReqMapping(desc = "下架公告", method = ReqMethod.POST)
    private void offlineNotice(HttpServletRequest req, HttpServletResponse resp){
        Integer id = RequestUtil.getIntParameter(req, "id");
        if(validParam(req, resp, id, "参数")){
            sysNoticeService.offlineNotice(id);
            PageJumpUtil.writeJsonOk("下架成功", resp);
        }
    }

    private void getLastNotice(HttpServletRequest req, HttpServletResponse resp){
        SysNoticeBean notice =  sysNoticeService.getLast();
        PageJumpUtil.writeJson(new HttpRespBean(notice), resp);
    }
    /****************************** 公告 end *******************************************/



    /****************************** 事件 begin *******************************************/
    /**
     * 事件列表
     * @param req
     * @param resp
     */
    private void eventList(HttpServletRequest req, HttpServletResponse resp){
        if(isAdmin(req, resp)){
            SqlQueryBean sqlQueryBean = SqlQueryBuilder.buildWhereSql(req);
            PageResult<SolrEventPublishBean> pageResult = eventPublishService.findPage(sqlQueryBean);
            req.setAttribute("pageResult", pageResult);
            PageJumpUtil.forward("eventList", req, resp);
        }
    }

    private void eventConsumeList(HttpServletRequest req, HttpServletResponse resp){
        if(isAdmin(req, resp)){
            String eventKey = RequestUtil.getStrParameter(req, "eventKey");
            if(validParam(req, resp, eventKey, "事件")){
                List<SolrEventConsumeBean> list = eventConsumeService.findList("event_key = '"+eventKey+"'");
                req.setAttribute("list", list);
                PageJumpUtil.writeJson(new HttpRespBean(list), resp);
            }
        }
    }

    /****************************** 事件 end *******************************************/
}
